package edu.nuist.shixun.api.product;

import com.mysql.cj.util.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import edu.nuist.shixun.table.Product;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
@CrossOrigin
@RestController
public class SaveProductAPI {
    @Resource
    JdbcTemplate jdbcTemplate;

    @PostMapping("/product/save")
    public Object handle(Product product){
        Map<String, String> map = new HashMap<>();
        if(StringUtils.isNullOrEmpty(product.getName())){
            map.put("code","-1");
            map.put("message","名称不能为空");
            return map;

        }
        if(product.getPrice()==null){
            map.put("code","-1");
            map.put("message","价格不能为空");
            return map;

        }
        String sql ="select count(*) from product where name = ?";
        Integer count = jdbcTemplate.queryForObject(sql,Integer.class,product.getName());
        if(count>0){
          map.put("code","-1");
           map.put("message","商品重复");
           return map;
       }
        sql = "insert into `product`(`name`,`brand`,`price`,`discount`,`stock`) values(?,?,?,?,?)";

        Object[] params={
                product.getName(),
                product.getBrand(),
                product.getPrice(),
                product.getDiscount(),
                product.getStock()
        };
    jdbcTemplate.update(sql,params);

    map.put("code","1");
    map.put("message","商品添加成功");
    return  map;
    }
}
